package homework.test1;

import java.util.Arrays;
import java.util.Scanner;

/*
二分法查找
int [] arr = {88,39,77,56,89,99,59,97};
 */
public class HalfSearch {
    public static void main(String[] args) {
        int [] arr = {88,39,77,56,89,99,59,97};
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入数字");
        String number = sc.next();
        int num = Integer.parseInt(number);

        int index = halfSearch(arr,num);
        System.out.println(Arrays.toString(arr));

        if(index == -1){
            System.out.println("数组不存在该数");
        }else {
            System.out.println("数组存在该数");
        }
    }

    public static int halfSearch(int [] arr, int number){
        bubbleSort(arr);

        int max = arr.length - 1;
        int min = 0;

        while (min <= max){
            int mid = (max + min) >> 1;
            if(number < arr[mid]){
                max = mid - 1;
            } else if (number > arr[mid]) {
                min = mid + 1;
            }else{
                return mid;
            }
        }

        return -1;
    }

    public static void bubbleSort(int [] arr){
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j+1]) {
                    arr[j] = arr[j] ^ arr[j+1];
                    arr[j+1] = arr[j] ^ arr[j+1];
                    arr[j] = arr[j] ^ arr[j+1];
                }
            }
        }
    }
}
